var db = require('bookshelf').bookshelf;
var util = require('util');
var moment = require('moment');
var Database = require('../app/database');
var TemplateBuilder = require('../app/template_builder');

var ConfigController = module.exports = {};

log = function(msg) {
    //console.log(new Date().toLocaleTimeString() + ' [config_controller]: ' + msg);
};

ConfigController.initialize = function(router) {
	log('initialize: ' + util.inspect(router,false,null));
	router.add({Method: router.Methods.GET, URL: 'configs', Authorize: router.Access.User, Handler: ConfigController.getConfigs})
	.add({Method: router.Methods.GET, URL: 'configs/:id', Authorize: router.Access.User, Handler: ConfigController.getConfig})
	.add({Method: router.Methods.GET, URL: 'configs/servers/:id', Authorize: router.Access.User, Handler: ConfigController.getServerConfig})
	.add({Method: router.Methods.POST, URL: 'configs', Authorize: router.Access.User, Handler: ConfigController.postConfig})
	.add({Method: router.Methods.DELETE, URL: 'configs/:id', Authorize: router.Access.Owner, Handler: ConfigController.deleteConfig})
};

ConfigController.getConfigs = function(req, res) {
	log('getConfigs: ' + req.originalUrl);
	new Database.Collections.Configs({})
		.fetch()
		.then(function(resp) {
			res.json(200, resp);
			log('replied: ' + util.inspect(resp,false,null));
		});
};
ConfigController.getConfig = function(req, res) {
	log('getConfig: ' + req.originalUrl);	
	new Database.Models.Config({config_id: req.params.id})
		.fetch()
		.then(function(resp) {
			if (!resp) {
				res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
			} else {
				res.json(200, resp);
			};
			log('replied: ' + util.inspect(resp,false,null));
		});
};

ConfigController.getServerConfig = function(req, res) {
	log('getServerConfig: ' + req.originalUrl);
	new Database.Collections.Configs()
		.query(function(qb) {
			qb.where('server_id', '=', req.params.id) //.andWhere('is_active', '!=', '0');
		})
		.fetch()
		.then(function(resp) {
			res.json(200, resp);
			log('replied: ' + util.inspect(resp,false,null));
		});
};

updateConfig = function(req,res,configArray,isArray,configModels,serverIds,idx) {
    var config = configArray[idx];
    var existing = new Database.Collections.Configs()
	.query(function(qb) {
		qb.where('server_id', '=', config.server_id).andWhere('name', '=', config.name)
        if (config.config_id) {
            qb.andWhere('config_id', '!=', config.config_id);
        };
	})
    .fetch()
    .then(function(resp) {
        if (resp == null || resp.length <= 0 || config.config_id > 0) {
			var model = new Database.Models.Config(config);
			model
				.save()
				.then(function(resp) {
                    if (resp != null) {
                        if (serverIds.indexOf(resp.get('server_id')) < 0) {
                            serverIds.push(resp.get('server_id'));
                        };
                        if (isArray) {
					        configModels.push(resp);
					        if (configModels.length == configArray.length) {
						        res.json(200, configModels);
						        log('replied: ' + util.inspect(configModels,false,null));
                                for (j = 0; j < serverIds.length; ++j) {
                                    TemplateBuilder.execute(serverIds[j]).then(function(value){
                                        log('Template Builder is done');
                                    });
                                };
					        };
                        } else {
						    res.json(200, resp);
						    log('replied: ' + util.inspect(resp,false,null));
                            for (j = 0; j < serverIds.length; j++) {
                                TemplateBuilder.execute(serverIds[j]).then(function(value){
                                    log('Template Builder is done');
                                });
                            };
                        };
                    } else {
                        res.json(500, { status: 500, type: 'Resource', message: 'Failes to save the configuration!' });
                    };
				});
        } else {
            if (isArray) {
				res.json(400, configModels);
				log('replied: ' + util.inspect(configModels,false,null));
            } else {
				res.json(500, { status: 500, type: 'Resource', message: 'Config already exists for that server' });
            };
        };
    });
};

ConfigController.postConfig = function(req, res) {
	log('postConfig: ' + req.originalUrl + ' - ' + util.inspect(req.body,false,null));
	if (req.body) {
        var isArray = (req.body instanceof Array);
		var configArray = [].concat( req.body );
		log('configArray: ' + util.inspect(configArray,false,null));
		var isValid = true;
		var configModels = [];
        var serverIds = [];
        if (configArray != null && configArray.length > 0) {
		    for (i = 0; i < configArray.length; i++) {
                updateConfig(req,res,configArray,isArray,configModels,serverIds,i);
		    };
        };
	} else {
		res.send(500,{ status: 500, type: 'Resource', message: 'Argument not valid' });
	};	
};

ConfigController.deleteConfig = function(req, res) {
	log('deleteConfig: ' + req.originalUrl);	
	new Database.Models.Config({config_id: req.params.id})
		.fetch()
		.then(function(resp) {
			if (resp) {
                if (resp.get('config_id') == req.params.id) {
                    resp.destroy().then(function(resp) {
                        log('deleteConfig: ' + resp);
				        res.json(200, { config_id: req.params.id });
                    });
                } else {
				    res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
                };
			} else {
				res.json(404, { status: 404, type: 'Resource', message: 'Not found' });
			};
			log('replied: ' + util.inspect(resp,false,null));
		});
};
